[[...path]].page.tsx 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607
  1. import React, { useEffect } from 'react';
  2. import EventEmitter from 'events';
  3. import {
  4. IDataWithMeta, IPageInfoForEntity, IPagePopulatedToShowRevision, isClient, isIPageInfoForEntity, IUser, IUserHasId, pagePathUtils, pathUtils,
  5. } from '@growi/core';
  6. import ExtensibleCustomError from 'extensible-custom-error';
  7. import { model as mongooseModel } from 'mongoose';
  8. import {
  9. NextPage, GetServerSideProps, GetServerSidePropsContext,
  10. } from 'next';
  11. import { serverSideTranslations } from 'next-i18next/serverSideTranslations';
  12. import dynamic from 'next/dynamic';
  13. import Head from 'next/head';
  14. import { useRouter } from 'next/router';
  15. import superjson from 'superjson';
  16. import { Comments } from '~/components/Comments';
  17. import { PageAlerts } from '~/components/PageAlert/PageAlerts';
  18. // import { useTranslation } from '~/i18n';
  19. import { CurrentPageContentFooter } from '~/components/PageContentFooter';
  20. import { UsersHomePageFooterProps } from '~/components/UsersHomePageFooter';
  21. import { CrowiRequest } from '~/interfaces/crowi-request';
  22. // import { renderScriptTagByName, renderHighlightJsStyleTag } from '~/service/cdn-resources-loader';
  23. // import { useIndentSize } from '~/stores/editor';
  24. // import { useRendererSettings } from '~/stores/renderer';
  25. // import { EditorMode, useEditorMode, useIsMobile } from '~/stores/ui';
  26. import { EditorConfig } from '~/interfaces/editor-settings';
  27. import { CustomWindow } from '~/interfaces/global';
  28. import { RendererConfig } from '~/interfaces/services/renderer';
  29. import { ISidebarConfig } from '~/interfaces/sidebar-config';
  30. import { IUserUISettings } from '~/interfaces/user-ui-settings';
  31. import { PageModel, PageDocument } from '~/server/models/page';
  32. import { PageRedirectModel } from '~/server/models/page-redirect';
  33. import { UserUISettingsModel } from '~/server/models/user-ui-settings';
  34. import { useSWRxCurrentPage, useSWRxIsGrantNormalized, useSWRxPageInfo } from '~/stores/page';
  35. import { useRedirectFrom } from '~/stores/page-redirect';
  36. import {
  37. usePreferDrawerModeByUser, usePreferDrawerModeOnEditByUser, useSidebarCollapsed, useCurrentSidebarContents, useCurrentProductNavWidth, useSelectedGrant,
  38. } from '~/stores/ui';
  39. import loggerFactory from '~/utils/logger';
  40. // import { isUserPage, isTrashPage, isSharedPage } from '~/utils/path-utils';
  41. // import GrowiSubNavigation from '../client/js/components/Navbar/GrowiSubNavigation';
  42. // import GrowiSubNavigationSwitcher from '../client/js/components/Navbar/GrowiSubNavigationSwitcher';
  43. import { DescendantsPageListModal } from '../components/DescendantsPageListModal';
  44. import { BasicLayout } from '../components/Layout/BasicLayout';
  45. import GrowiContextualSubNavigation from '../components/Navbar/GrowiContextualSubNavigation';
  46. import DisplaySwitcher from '../components/Page/DisplaySwitcher';
  47. // import { serializeUserSecurely } from '../server/models/serializers/user-serializer';
  48. // import PageStatusAlert from '../client/js/components/PageStatusAlert';
  49. import {
  50. useCurrentUser, useCurrentPagePath,
  51. useIsLatestRevision,
  52. useIsForbidden, useIsNotFound, useIsTrashPage, useIsSharedUser,
  53. useIsEnabledStaleNotification, useIsIdenticalPath,
  54. useIsSearchServiceConfigured, useIsSearchServiceReachable, useDisableLinkSharing,
  55. useDrawioUri, useHackmdUri,
  56. useIsAclEnabled, useIsUserPage,
  57. useCsrfToken, useIsSearchScopeChildrenAsDefault, useCurrentPageId, useCurrentPathname,
  58. useIsSlackConfigured, useRendererConfig, useEditingMarkdown,
  59. useEditorConfig, useIsAllReplyShown, useIsUploadableFile, useIsUploadableImage,
  60. } from '../stores/context';
  61. import {
  62. CommonProps, getNextI18NextConfig, getServerSideCommonProps, useCustomTitle,
  63. } from './utils/commons';
  64. import { useSWRxLayoutSetting } from '~/stores/admin/customize';
  65. // import { useCurrentPageSWR } from '../stores/page';
  66. const NotCreatablePage = dynamic(() => import('../components/NotCreatablePage').then(mod => mod.NotCreatablePage), { ssr: false });
  67. const ForbiddenPage = dynamic(() => import('../components/ForbiddenPage'), { ssr: false });
  68. const UnsavedAlertDialog = dynamic(() => import('./UnsavedAlertDialog'), { ssr: false });
  69. const GrowiSubNavigationSwitcher = dynamic(() => import('../components/Navbar/GrowiSubNavigationSwitcher'), { ssr: false });
  70. const UsersHomePageFooter = dynamic<UsersHomePageFooterProps>(() => import('../components/UsersHomePageFooter')
  71. .then(mod => mod.UsersHomePageFooter), { ssr: false });
  72. const logger = loggerFactory('growi:pages:all');
  73. const {
  74. isPermalink: _isPermalink, isUsersHomePage, isTrashPage: _isTrashPage, isUserPage, isCreatablePage, isTopPage,
  75. } = pagePathUtils;
  76. const { removeHeadingSlash } = pathUtils;
  77. type IPageToShowRevisionWithMeta = IDataWithMeta<IPagePopulatedToShowRevision & PageDocument, IPageInfoForEntity>;
  78. type IPageToShowRevisionWithMetaSerialized = IDataWithMeta<string, string>;
  79. superjson.registerCustom<IPageToShowRevisionWithMeta, IPageToShowRevisionWithMetaSerialized>(
  80. {
  81. isApplicable: (v): v is IPageToShowRevisionWithMeta => {
  82. return v?.data != null
  83. && v?.data.toObject != null
  84. && v?.meta != null
  85. && isIPageInfoForEntity(v.meta);
  86. },
  87. serialize: (v) => {
  88. return {
  89. data: superjson.stringify(v.data.toObject()),
  90. meta: superjson.stringify(v.meta),
  91. };
  92. },
  93. deserialize: (v) => {
  94. return {
  95. data: superjson.parse(v.data),
  96. meta: v.meta != null ? superjson.parse(v.meta) : undefined,
  97. };
  98. },
  99. },
  100. 'IPageToShowRevisionWithMetaTransformer',
  101. );
  102. const IdenticalPathPage = (): JSX.Element => {
  103. const IdenticalPathPage = dynamic(() => import('../components/IdenticalPathPage').then(mod => mod.IdenticalPathPage), { ssr: false });
  104. return <IdenticalPathPage />;
  105. };
  106. const PutbackPageModal = (): JSX.Element => {
  107. const PutbackPageModal = dynamic(() => import('../components/PutbackPageModal'), { ssr: false });
  108. return <PutbackPageModal />;
  109. };
  110. type Props = CommonProps & {
  111. currentUser: IUser,
  112. pageWithMeta: IPageToShowRevisionWithMeta | null,
  113. // pageUser?: any,
  114. redirectFrom?: string;
  115. // shareLinkId?: string;
  116. isLatestRevision?: boolean
  117. isIdenticalPathPage?: boolean,
  118. isForbidden: boolean,
  119. isNotFound: boolean,
  120. isNotCreatablePage: boolean,
  121. // isAbleToDeleteCompletely: boolean,
  122. isSearchServiceConfigured: boolean,
  123. isSearchServiceReachable: boolean,
  124. isSearchScopeChildrenAsDefault: boolean,
  125. isSlackConfigured: boolean,
  126. // isMailerSetup: boolean,
  127. isAclEnabled: boolean,
  128. // hasSlackConfig: boolean,
  129. drawioUri: string,
  130. hackmdUri: string,
  131. noCdn: string,
  132. // highlightJsStyle: string,
  133. isAllReplyShown: boolean,
  134. // isContainerFluid: boolean,
  135. editorConfig: EditorConfig,
  136. isEnabledStaleNotification: boolean,
  137. // isEnabledLinebreaks: boolean,
  138. // isEnabledLinebreaksInComments: boolean,
  139. // adminPreferredIndentSize: number,
  140. // isIndentSizeForced: boolean,
  141. disableLinkSharing: boolean,
  142. rendererConfig: RendererConfig,
  143. // UI
  144. userUISettings?: IUserUISettings
  145. // Sidebar
  146. sidebarConfig: ISidebarConfig,
  147. };
  148. const GrowiPage: NextPage<Props> = (props: Props) => {
  149. // const { t } = useTranslation();
  150. const router = useRouter();
  151. const { data: currentUser } = useCurrentUser(props.currentUser ?? null);
  152. // register global EventEmitter
  153. if (isClient()) {
  154. (window as CustomWindow).globalEmitter = new EventEmitter();
  155. }
  156. // commons
  157. useEditorConfig(props.editorConfig);
  158. useCsrfToken(props.csrfToken);
  159. // UserUISettings
  160. usePreferDrawerModeByUser(props.userUISettings?.preferDrawerModeByUser ?? props.sidebarConfig.isSidebarDrawerMode);
  161. usePreferDrawerModeOnEditByUser(props.userUISettings?.preferDrawerModeOnEditByUser);
  162. useSidebarCollapsed(props.userUISettings?.isSidebarCollapsed ?? props.sidebarConfig.isSidebarClosedAtDockMode);
  163. useCurrentSidebarContents(props.userUISettings?.currentSidebarContents);
  164. useCurrentProductNavWidth(props.userUISettings?.currentProductNavWidth);
  165. // page
  166. useIsLatestRevision(props.isLatestRevision);
  167. // useOwnerOfCurrentPage(props.pageUser != null ? JSON.parse(props.pageUser) : null);
  168. useIsForbidden(props.isForbidden);
  169. useIsNotFound(props.isNotFound);
  170. // useIsNotCreatable(props.IsNotCreatable);
  171. useRedirectFrom(props.redirectFrom);
  172. // useShared();
  173. // useShareLinkId(props.shareLinkId);
  174. useIsSharedUser(false); // this page cann't be routed for '/share'
  175. useIsIdenticalPath(false); // TODO: need to initialize from props
  176. // useIsAbleToDeleteCompletely(props.isAbleToDeleteCompletely);
  177. useIsEnabledStaleNotification(props.isEnabledStaleNotification);
  178. useIsSearchServiceConfigured(props.isSearchServiceConfigured);
  179. useIsSearchServiceReachable(props.isSearchServiceReachable);
  180. useIsSearchScopeChildrenAsDefault(props.isSearchScopeChildrenAsDefault);
  181. useIsSlackConfigured(props.isSlackConfigured);
  182. // useIsMailerSetup(props.isMailerSetup);
  183. useIsAclEnabled(props.isAclEnabled);
  184. // useHasSlackConfig(props.hasSlackConfig);
  185. useDrawioUri(props.drawioUri);
  186. useHackmdUri(props.hackmdUri);
  187. // useNoCdn(props.noCdn);
  188. // useIndentSize(props.adminPreferredIndentSize);
  189. useDisableLinkSharing(props.disableLinkSharing);
  190. useRendererConfig(props.rendererConfig);
  191. // useRendererSettings(props.rendererSettingsStr != null ? JSON.parse(props.rendererSettingsStr) : undefined);
  192. // useGrowiRendererConfig(props.growiRendererConfigStr != null ? JSON.parse(props.growiRendererConfigStr) : undefined);
  193. useIsAllReplyShown(props.isAllReplyShown);
  194. useIsUploadableFile(props.editorConfig.upload.isUploadableFile);
  195. useIsUploadableImage(props.editorConfig.upload.isUploadableImage);
  196. // const { data: editorMode } = useEditorMode();
  197. const { pageWithMeta, userUISettings } = props;
  198. useSWRxCurrentPage(undefined, pageWithMeta?.data ?? null); // store initial data
  199. useEditingMarkdown(pageWithMeta?.data.revision?.body ?? '');
  200. const pageId = pageWithMeta?.data._id;
  201. const pagePath = pageWithMeta?.data.path ?? (!_isPermalink(props.currentPathname) ? props.currentPathname : undefined);
  202. useCurrentPageId(pageId ?? null);
  203. useIsUserPage(pagePath != null && isUserPage(pagePath));
  204. // useIsNotCreatable(props.isForbidden || !isCreatablePage(pagePath)); // TODO: need to include props.isIdentical
  205. useCurrentPagePath(pagePath);
  206. useCurrentPathname(props.currentPathname);
  207. useIsTrashPage(pagePath != null && _isTrashPage(pagePath));
  208. const { data: layoutSetting } = useSWRxLayoutSetting({ isContainerFluid: props.isContainerFluid });
  209. const { data: dataPageInfo } = useSWRxPageInfo(pageId);
  210. const { data: grantData } = useSWRxIsGrantNormalized(pageId);
  211. const { mutate: mutateSelectedGrant } = useSelectedGrant();
  212. const shouldRenderPutbackPageModal = pageWithMeta != null
  213. ? _isTrashPage(pageWithMeta.data.path)
  214. : false;
  215. // sync grant data
  216. useEffect(() => {
  217. mutateSelectedGrant(grantData?.grantData.currentPageGrant);
  218. }, [grantData?.grantData.currentPageGrant, mutateSelectedGrant]);
  219. // sync pathname by Shallow Routing https://nextjs.org/docs/routing/shallow-routing
  220. useEffect(() => {
  221. const decodedURI = decodeURI(window.location.pathname);
  222. if (isClient() && decodedURI !== props.currentPathname) {
  223. router.replace(props.currentPathname, undefined, { shallow: true });
  224. }
  225. }, [props.currentPathname, router]);
  226. const classNames: string[] = [];
  227. // switch (editorMode) {
  228. // case EditorMode.Editor:
  229. // classNames.push('on-edit', 'builtin-editor');
  230. // break;
  231. // case EditorMode.HackMD:
  232. // classNames.push('on-edit', 'hackmd');
  233. // break;
  234. // }
  235. // if (page == null) {
  236. // classNames.push('not-found-page');
  237. // }
  238. const isTopPagePath = isTopPage(pageWithMeta?.data.path ?? '');
  239. // Use `props.isContainerFluid` as default, `layoutSetting.isContainerFluid` as admin setting, `dataPageInfo.expandContentWidth` as each page's setting
  240. const expandContentWidth = dataPageInfo == null || !('expandContentWidth' in dataPageInfo)
  241. ? layoutSetting?.isContainerFluid ?? props.isContainerFluid
  242. : dataPageInfo.expandContentWidth ?? layoutSetting?.isContainerFluid ?? props.isContainerFluid;
  243. return (
  244. <>
  245. <Head>
  246. {/*
  247. {renderScriptTagByName('drawio-viewer')}
  248. {renderScriptTagByName('highlight-addons')}
  249. {renderHighlightJsStyleTag(props.highlightJsStyle)}
  250. */}
  251. </Head>
  252. {/* <BasicLayout title={useCustomTitle(props, t('GROWI'))} className={classNames.join(' ')}> */}
  253. <BasicLayout
  254. title={useCustomTitle(props, 'GROWI')}
  255. className={classNames.join(' ')}
  256. expandContainer={expandContentWidth ?? props.isContainerFluid}
  257. >
  258. <div className="h-100 d-flex flex-column justify-content-between">
  259. <header className="py-0 position-relative">
  260. <GrowiContextualSubNavigation isLinkSharingDisabled={props.disableLinkSharing} />
  261. </header>
  262. <div className="d-edit-none">
  263. <GrowiSubNavigationSwitcher />
  264. </div>
  265. <div id="grw-subnav-sticky-trigger" className="sticky-top"></div>
  266. <div id="grw-fav-sticky-trigger" className="sticky-top"></div>
  267. <div className="flex-grow-1">
  268. <div id="main" className={`main ${isUsersHomePage(props.currentPathname) && 'user-page'}`}>
  269. <div id="content-main" className="content-main grw-container-convertible">
  270. { props.isIdenticalPathPage && <IdenticalPathPage /> }
  271. { !props.isIdenticalPathPage && (
  272. <>
  273. <PageAlerts />
  274. { props.isForbidden && <ForbiddenPage /> }
  275. { props.isNotCreatablePage && <NotCreatablePage />}
  276. { !props.isForbidden && !props.isNotCreatablePage && <DisplaySwitcher />}
  277. {/* <DisplaySwitcher /> */}
  278. {/* <PageStatusAlert /> */}
  279. </>
  280. ) }
  281. {/* <div className="col-xl-2 col-lg-3 d-none d-lg-block revision-toc-container">
  282. <div id="revision-toc" className="revision-toc mt-3 sps sps--abv" data-sps-offset="123">
  283. <div id="revision-toc-content" className="revision-toc-content"></div>
  284. </div>
  285. </div> */}
  286. </div>
  287. </div>
  288. </div>
  289. { !props.isIdenticalPathPage && !props.isNotFound && (
  290. <footer className="footer d-edit-none">
  291. { pageWithMeta != null && !isTopPagePath && (<Comments pageId={pageId} revision={pageWithMeta.data.revision} />) }
  292. { pageWithMeta != null && isUsersHomePage(pageWithMeta.data.path) && (
  293. <UsersHomePageFooter creatorId={pageWithMeta.data.creator._id}/>
  294. ) }
  295. <CurrentPageContentFooter />
  296. </footer>
  297. )}
  298. <UnsavedAlertDialog />
  299. <DescendantsPageListModal />
  300. {shouldRenderPutbackPageModal && <PutbackPageModal />}
  301. </div>
  302. </BasicLayout>
  303. </>
  304. );
  305. };
  306. function getPageIdFromPathname(currentPathname: string): string | null {
  307. return _isPermalink(currentPathname) ? removeHeadingSlash(currentPathname) : null;
  308. }
  309. class MultiplePagesHitsError extends ExtensibleCustomError {
  310. pagePath: string;
  311. constructor(pagePath: string) {
  312. super(`MultiplePagesHitsError occured by '${pagePath}'`);
  313. this.pagePath = pagePath;
  314. }
  315. }
  316. async function injectPageData(context: GetServerSidePropsContext, props: Props): Promise<void> {
  317. const req: CrowiRequest = context.req as CrowiRequest;
  318. const { crowi } = req;
  319. const { revisionId } = req.query;
  320. const Page = crowi.model('Page') as PageModel;
  321. const PageRedirect = mongooseModel('PageRedirect') as PageRedirectModel;
  322. const { pageService } = crowi;
  323. let currentPathname = props.currentPathname;
  324. const pageId = getPageIdFromPathname(currentPathname);
  325. const isPermalink = _isPermalink(currentPathname);
  326. const { user } = req;
  327. if (!isPermalink) {
  328. // check redirects
  329. const chains = await PageRedirect.retrievePageRedirectEndpoints(currentPathname);
  330. if (chains != null) {
  331. // overwrite currentPathname
  332. currentPathname = chains.end.toPath;
  333. props.currentPathname = currentPathname;
  334. // set redirectFrom
  335. props.redirectFrom = chains.start.fromPath;
  336. }
  337. // check whether the specified page path hits to multiple pages
  338. const count = await Page.countByPathAndViewer(currentPathname, user, null, true);
  339. if (count > 1) {
  340. throw new MultiplePagesHitsError(currentPathname);
  341. }
  342. }
  343. const pageWithMeta: IPageToShowRevisionWithMeta | null = await pageService.findPageAndMetaDataByViewer(pageId, currentPathname, user, true); // includeEmpty = true, isSharedPage = false
  344. const page = pageWithMeta?.data as unknown as PageDocument;
  345. // add user to seen users
  346. if (page != null && user != null) {
  347. await page.seen(user);
  348. }
  349. // populate & check if the revision is latest
  350. if (page != null) {
  351. page.initLatestRevisionField(revisionId);
  352. await page.populateDataToShowRevision();
  353. props.isLatestRevision = page.isLatestRevision();
  354. props.isContainerFluid = page.expandContentWidth ?? props.isContainerFluid;
  355. }
  356. props.pageWithMeta = pageWithMeta;
  357. }
  358. async function injectUserUISettings(context: GetServerSidePropsContext, props: Props): Promise<void> {
  359. const req = context.req as CrowiRequest<IUserHasId & any>;
  360. const { user } = req;
  361. const UserUISettings = mongooseModel('UserUISettings') as UserUISettingsModel;
  362. const userUISettings = user == null ? null : await UserUISettings.findOne({ user: user._id }).exec();
  363. if (userUISettings != null) {
  364. props.userUISettings = userUISettings.toObject();
  365. }
  366. }
  367. async function injectRoutingInformation(context: GetServerSidePropsContext, props: Props): Promise<void> {
  368. const req: CrowiRequest = context.req as CrowiRequest;
  369. const { crowi } = req;
  370. const Page = crowi.model('Page') as PageModel;
  371. const { currentPathname } = props;
  372. const pageId = getPageIdFromPathname(currentPathname);
  373. const isPermalink = _isPermalink(currentPathname);
  374. const page = props.pageWithMeta?.data;
  375. if (props.isIdenticalPathPage) {
  376. // TBD
  377. }
  378. else if (page == null) {
  379. props.isNotFound = true;
  380. props.isNotCreatablePage = !isCreatablePage(currentPathname);
  381. // check the page is forbidden or just does not exist.
  382. const count = isPermalink ? await Page.count({ _id: pageId }) : await Page.count({ path: currentPathname });
  383. props.isForbidden = count > 0;
  384. }
  385. else {
  386. props.isNotFound = page.isEmpty;
  387. // /62a88db47fed8b2d94f30000 ==> /path/to/page
  388. if (isPermalink && page.isEmpty) {
  389. props.currentPathname = page.path;
  390. }
  391. // /path/to/page ==> /62a88db47fed8b2d94f30000
  392. if (!isPermalink && !page.isEmpty) {
  393. const isToppage = pagePathUtils.isTopPage(props.currentPathname);
  394. if (!isToppage) {
  395. props.currentPathname = `/${page._id}`;
  396. }
  397. }
  398. }
  399. }
  400. // async function injectPageUserInformation(context: GetServerSidePropsContext, props: Props): Promise<void> {
  401. // const req: CrowiRequest = context.req as CrowiRequest;
  402. // const { crowi } = req;
  403. // const UserModel = crowi.model('User');
  404. // if (isUserPage(props.currentPagePath)) {
  405. // const user = await UserModel.findUserByUsername(UserModel.getUsernameByPath(props.currentPagePath));
  406. // if (user != null) {
  407. // props.pageUser = JSON.stringify(user.toObject());
  408. // }
  409. // }
  410. // }
  411. function injectServerConfigurations(context: GetServerSidePropsContext, props: Props): void {
  412. const req: CrowiRequest = context.req as CrowiRequest;
  413. const { crowi } = req;
  414. const {
  415. appService, searchService, configManager, aclService, slackNotificationService, mailService,
  416. } = crowi;
  417. props.isSearchServiceConfigured = searchService.isConfigured;
  418. props.isSearchServiceReachable = searchService.isReachable;
  419. props.isSearchScopeChildrenAsDefault = configManager.getConfig('crowi', 'customize:isSearchScopeChildrenAsDefault');
  420. props.isSlackConfigured = crowi.slackIntegrationService.isSlackConfigured;
  421. // props.isMailerSetup = mailService.isMailerSetup;
  422. props.isAclEnabled = aclService.isAclEnabled();
  423. // props.hasSlackConfig = slackNotificationService.hasSlackConfig();
  424. props.drawioUri = configManager.getConfig('crowi', 'app:drawioUri');
  425. props.hackmdUri = configManager.getConfig('crowi', 'app:hackmdUri');
  426. props.noCdn = configManager.getConfig('crowi', 'app:noCdn');
  427. // props.highlightJsStyle = configManager.getConfig('crowi', 'customize:highlightJsStyle');
  428. props.isAllReplyShown = configManager.getConfig('crowi', 'customize:isAllReplyShown');
  429. // props.isContainerFluid = configManager.getConfig('crowi', 'customize:isContainerFluid');
  430. props.isEnabledStaleNotification = configManager.getConfig('crowi', 'customize:isEnabledStaleNotification');
  431. // props.isEnabledLinebreaks = configManager.getConfig('markdown', 'markdown:isEnabledLinebreaks');
  432. // props.isEnabledLinebreaksInComments = configManager.getConfig('markdown', 'markdown:isEnabledLinebreaksInComments');
  433. props.disableLinkSharing = configManager.getConfig('crowi', 'security:disableLinkSharing');
  434. props.editorConfig = {
  435. upload: {
  436. isUploadableFile: crowi.fileUploadService.getFileUploadEnabled(),
  437. isUploadableImage: crowi.fileUploadService.getIsUploadable(),
  438. },
  439. };
  440. // props.adminPreferredIndentSize = configManager.getConfig('markdown', 'markdown:adminPreferredIndentSize');
  441. // props.isIndentSizeForced = configManager.getConfig('markdown', 'markdown:isIndentSizeForced');
  442. props.rendererConfig = {
  443. isEnabledLinebreaks: configManager.getConfig('markdown', 'markdown:isEnabledLinebreaks'),
  444. isEnabledLinebreaksInComments: configManager.getConfig('markdown', 'markdown:isEnabledLinebreaksInComments'),
  445. adminPreferredIndentSize: configManager.getConfig('markdown', 'markdown:adminPreferredIndentSize'),
  446. isIndentSizeForced: configManager.getConfig('markdown', 'markdown:isIndentSizeForced'),
  447. plantumlUri: process.env.PLANTUML_URI ?? null,
  448. blockdiagUri: process.env.BLOCKDIAG_URI ?? null,
  449. // XSS Options
  450. isEnabledXssPrevention: configManager.getConfig('markdown', 'markdown:xss:isEnabledPrevention'),
  451. attrWhiteList: crowi.xssService.getAttrWhiteList(),
  452. tagWhiteList: crowi.xssService.getTagWhiteList(),
  453. highlightJsStyleBorder: crowi.configManager.getConfig('crowi', 'customize:highlightJsStyleBorder'),
  454. };
  455. props.sidebarConfig = {
  456. isSidebarDrawerMode: configManager.getConfig('crowi', 'customize:isSidebarDrawerMode'),
  457. isSidebarClosedAtDockMode: configManager.getConfig('crowi', 'customize:isSidebarClosedAtDockMode'),
  458. };
  459. }
  460. /**
  461. * for Server Side Translations
  462. * @param context
  463. * @param props
  464. * @param namespacesRequired
  465. */
  466. async function injectNextI18NextConfigurations(context: GetServerSidePropsContext, props: Props, namespacesRequired?: string[] | undefined): Promise<void> {
  467. const nextI18NextConfig = await getNextI18NextConfig(serverSideTranslations, context, namespacesRequired);
  468. props._nextI18Next = nextI18NextConfig._nextI18Next;
  469. }
  470. export const getServerSideProps: GetServerSideProps = async(context: GetServerSidePropsContext) => {
  471. const req = context.req as CrowiRequest<IUserHasId & any>;
  472. const { user } = req;
  473. const result = await getServerSideCommonProps(context);
  474. // check for presence
  475. // see: https://github.com/vercel/next.js/issues/19271#issuecomment-730006862
  476. if (!('props' in result)) {
  477. throw new Error('invalid getSSP result');
  478. }
  479. const props: Props = result.props as Props;
  480. if (props.redirectDestination != null) {
  481. return {
  482. redirect: {
  483. permanent: false,
  484. destination: props.redirectDestination,
  485. },
  486. };
  487. }
  488. if (user != null) {
  489. props.currentUser = user.toObject();
  490. }
  491. try {
  492. await injectPageData(context, props);
  493. }
  494. catch (err) {
  495. if (err instanceof MultiplePagesHitsError) {
  496. props.isIdenticalPathPage = true;
  497. }
  498. else {
  499. throw err;
  500. }
  501. }
  502. await injectUserUISettings(context, props);
  503. await injectRoutingInformation(context, props);
  504. injectServerConfigurations(context, props);
  505. await injectNextI18NextConfigurations(context, props, ['translation']);
  506. return {
  507. props,
  508. };
  509. };
  510. export default GrowiPage;